package com.scorekeeper.objects;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcel;

import com.scorekeeper.utils.DBProvider;

public final class Division 
	extends DBProvider 
	implements DBObject
{
	
	public int _id;
	public String name;
	public String acro;
	
	public Division(Context context) {
		super(context);
		this._id = -1;
	}
	
	@Override
	public int describeContents() { return hashCode(); }
	
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(this._id);
		dest.writeString(this.name);
		dest.writeString(this.acro);
	}

	@Override
	public void loadFromParcel(Parcel loadFrom) {
		this._id = loadFrom.readInt();
		this.name = loadFrom.readString();
		this.acro = loadFrom.readString();
	}

	@Override
	public void save() {
		this.open();
		
		if (this._id != -1) {
			//update
			this.update(Table.DIVISION.Name(), loadContentValues(), "Id=?", new String[] { Integer.toString(this._id) } );
		} else {
			//insert
			this._id = (int) this.insert(Table.DIVISION.Name(), loadContentValues());
		}
		
		this.close();
	}
	
	@Override
	public void delete() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ContentValues loadContentValues() {
		ContentValues cv = new ContentValues();
		
		cv.put("DivisionName", this.name);
		cv.put("DivisionAcro", this.acro);
		
		return cv;
	}

	@Override
	public boolean load(int id) {
		this._id = id;
		return load();
	}
	
	@Override
	public boolean load() {
		boolean rv = false;
		
		this.open();
		
		//ensure a valid id
		if (this._id != -1) {
			Cursor cur = this.select("SELECT * FROM DIVISION WHERE Id = ?", new String[] { Integer.toString(this._id) });
			if (this.isValidCursor(cur)) {
				this._id = cur.getInt(0);
				this.name = cur.getString(1);
				this.acro = cur.getString(2);
				rv = true;
			}
		}
		
		this.close();
		
		return rv;
	}
	
	public boolean load(String divisionName) {
		
		this.open();
		
		Cursor cur = this.select("SELECT ID FROM DIVISION WHERE DivisionName = ?", new String[] { divisionName });
		if (this.isValidCursor(cur)) {
			this._id = cur.getInt(0);
		}
		
		this.close();
		
		return load();
	}
}
